package com.boot.service;

import com.boot.pojo.BankAccount;

import java.io.PrintStream;
import java.util.concurrent.TimeUnit;

public class BankTransferSystem {
    public static void main(String[] args) {
        BankAccount accountA = new BankAccount("A", 1000);
        BankAccount accountB = new BankAccount("B", 1000);
        try {
            PrintStream fileOut = new PrintStream("./transfer.log");
            System.setOut(fileOut); // 重定向标准输出
        } catch (Exception e) {
            e.printStackTrace();
        }

        //模拟多线程转账
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    accountA.transfer(accountB, 50);
                    Thread.sleep(100);  //模拟处理时间
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }, "Transfer A to B");

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    accountB.transfer(accountA, 30);
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }, "Transfer B to A");

        Thread t3 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    boolean success = accountA.tryTransfer(accountB, 70, 300, TimeUnit.MILLISECONDS);
                    System.out.println("尝试转账结果：" + success);
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }, "TryTransfer-Thread");

        t1.start();
        t2.start();
        t3.start();

        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        // 打印最终余额
        System.out.println("最终余额:");
        System.out.println(accountA);
        System.out.println(accountB);
    }
}

